package com.ferry.controller;


import com.ferry.domain.WallType;
import com.ferry.service.WallService;
import com.ferry.service.WallTypeService;
import com.ferry.utils.DateUtils;
import com.ferry.utils.IpUtils;
import com.ferry.utils.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

@Controller
@Slf4j
public class UploadController {


    @Autowired
    private WallTypeService wallTypeService;

    @Autowired
    private WallService wallService;

    @GetMapping("/upload")
    public String upload(HttpServletRequest request, Model model) {
        log.info("时间:" + DateUtils.getCurrentDate() + ",IP:" + IpUtils.getIpAddress(request) + "访问上传！");
        List<WallType> all = wallTypeService.getAll();
        model.addAttribute("types",all);
        return "upload";
    }


    @PostMapping("/upload")
    public String upload(MultipartFile file, Long typeId,
                         @RequestParam(required = false,defaultValue = "0") Integer price, Model model) {
        log.info("时间:" + DateUtils.getCurrentDate()+ "," + file.getOriginalFilename() +",类型:" + typeId +",价格:"+ price + "被上传！");
        List<WallType> all = wallTypeService.getAll();
        model.addAttribute("types",all);
        try {
            Response response = wallService.addWall(file.getInputStream(),
                    file.getOriginalFilename(),
                    file.getSize(), typeId, price);
            model.addAttribute("msg",response.getMassage());
            return "upload";
        } catch (IOException e) {
            e.printStackTrace();
        }
        model.addAttribute("msg","系统错误");
        return "upload";
    }

}
